const {
  getList,
  findOne,
  addData,
  updateData,
} = require("../utils/list");

let userList = require("../database/user.json").data

let prefix = "/geeker/user";

function filterByAge(list, maxAge, minAge) {
  if (typeof maxAge === 'undefined' || typeof minAge === 'undefined') {
    return list;
  }
  return list.filter(item => {
    const age = item.user?.detail?.age
    return age <= maxAge && age >= minAge
  })
}

function createRoute(app, root_prefix) {
	prefix = root_prefix + prefix

  app.post(`${prefix}/list`, (req, res) => {
		const { type, maxAge, minAge, ...rest } = req.body
    const data = getList(userList, rest, (list) => filterByAge(list, maxAge, minAge));
    data.list = data.list.map(item => {
      const { age, ...rest } = item
      if (!rest.user) {
        rest.user = {
          detail: {}
        }
      }
      rest.user.detail.age = age
      return rest
    })
    res.send({
      code: 200,
      data,
      msg: 'success',
      success: true,
    });
  });

  app.get(`${prefix}/:id`, (req, res) => {
    const data = findOne(userList, req.query.id);
    res.send({
      code: 200,
      data,
      msg: 'success',
      success: true,
    });
  });

  app.post(`${prefix}/`, (req, res) => {
    const data = addData(userList, req.body);
    res.send({
      code: 200,
      data: data.id,
      msg: 'success',
      success: true,
    });
  });

  app.put(`${prefix}/`, (req, res) => {
    const data = updateData(userList, req.body);
    res.send({
      code: 200,
      msg: 'success',
      success: true,
    });
  });

  app.delete(`${prefix}/:ids`, (req, res) => {
    const { ids } = req.params;
    if (!ids && ids !== 0) {
      res.send({
        code: 450,
        msg: '缺少ids参数',
        success: false,
      });
    } else {
      const arr = ids.split(",")
      userList = userList.filter((item) => !arr.includes(item.id))
      res.send({
        code: 200,
        msg: 'success',
        success: true,
      });
    }
  });
}
module.exports = createRoute;
